﻿using System;
using System.Collections.Generic;
using System.Linq;
using BL;
using BL.Model.Request;
using Common;
using DAL.Model;
using Nicekit.Excel;
using UI.Base;

namespace UI.Reports
{
    public partial class frmCustomerLiability : DialogViewBase
    {
        private MasterSession _session;
        private ReportController _reportController;
        private CustomerController _customerController;
        List<GetCustomerLiability> _reportData;
        List<Customer> _customers;

        public frmCustomerLiability ()
        {
            InitializeComponent();
        }

        protected override void InitializeBO()
        {
            base.InitializeBO();
            _session = new MasterSession();
            _reportController = new ReportController(_session);
            _customerController = new CustomerController(_session);
        }

        protected override void PopulateData ()
        {
            base.PopulateData();

            var customer = cboCustomers.EditValue != null && cboCustomers.EditValue.ToString() != "-1"
                               ? cboCustomers.EditValue.ToString()
                               : string.Join(",", _customers.Select(t => t.Id).ToArray());
            _reportData = _reportController.GetLiabilityDetails(daFromDate.DateTime,
                                                                          daToDate.DateTime,
                                                                          customer);
            
            decimal? endLiability = 0;
            decimal? startLiability = 0;
            var customerName = string.Empty;
            foreach (var liability in _reportData)
            {
                // reset liability for each customer
                if (liability.Customer != customerName)
                {
                    customerName = liability.Customer;

                    startLiability = liability.StartLiability.HasValue
                                        ? liability.StartLiability
                                        : 0;
                    endLiability = 0;
                }

                endLiability = startLiability +
                                    (endLiability.HasValue
                                            ? endLiability
                                            : 0) +
                                    (liability.Spend.HasValue
                                            ? liability.Spend
                                            : 0) -
                                    (liability.Receipt.HasValue
                                            ? liability.Receipt
                                            : 0) -
                                    (liability.Discount.HasValue
                                            ? liability.Discount
                                            : 0);
                startLiability = 0;
                liability.EndLiability = endLiability;
            }

            var customerLiability = new GetCustomerLiability
            {
                Customer = "Tổng cộng nợ cuối",
                Quantity = 0,
                StartLiability = 0,
                Spend = 0,
                Receipt = 0,
                Discount = 0
            };

            _reportData
                .ForEach(t =>
                             {
                                 customerLiability.Quantity += t.Quantity.HasValue ? t.Quantity : 0;
                                 customerLiability.StartLiability += t.StartLiability.HasValue ? t.StartLiability : 0;
                                 customerLiability.Spend += t.Spend.HasValue ? t.Spend : 0;
                                 customerLiability.Receipt += t.Receipt.HasValue ? t.Receipt : 0;
                                 customerLiability.Discount += t.Discount.HasValue ? t.Discount : 0;
                             });
            var totalLiability = _reportData.Where(t => t.DocNo == null &&
                                                        !t.StartLiability.HasValue)
                .Sum(t => t.EndLiability);
            customerLiability.EndLiability = totalLiability;

            _reportData.Add(customerLiability);

            dgLiabilities.DataSource = _reportData;
            gvLiabilities.ExpandAllGroups();
            gvLiabilities.BestFitColumns();

            PrecisionHelper.FormatCurencyPrecision(gcStartLiability,
                                                   gcQuantity,
                                                   gcUnitPrice,
                                                   gcSpend,
                                                   gcReceipt,
                                                   gcDiscount,
                                                   gcEndLiability);
        }

        protected override void PopulateStaticData()
        {
            base.PopulateStaticData();

            daFromDate.DateTime = CommonHelper.FirstDayOfMonth(DateTime.Now);
            daToDate.DateTime = CommonHelper.LastDayOfMonth(DateTime.Now);
            LoadCustomer();
        }

        private void spFind_Click (object sender, EventArgs e)
        {
            PopulateData();
        }

        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            if (_reportData == null || !_reportData.Any())
            {
                return;
            }

            Excel.dataGridViewToExcel(gridSummary, 1, 1, null, null);
        }

        #region Private methods

/*
        [Obsolete("Rewrite using store proc")]
        private void BindSummaryGrid()
        {
            #region Obsoleted: Rewrite using store proc below
            //var request = new ReportLiabilityRequest
            //                  {
            //                      FromDate = daFromDate.DateTime,
            //                      ToDate = daToDate.DateTime
            //                  };
            //var customer = cboCustomers.GetSelectedDataRow() as Customer;
            //if (customer != null)
            //{
            //    request.CustomerIds = new List<int> {customer.Id};
            //}
            //_reportData = _reportController.GetLiabilityReport(request);
            //gridMain.DataSource = _reportData;

            //var rowCount = _reportData.Count;
            //for (int i = 0; i < rowCount; i++)
            //{
            //    gridSummary.ExpandMasterRow(i);
            //}
            #endregion
        }
*/

        void LoadCustomer()
        {
            var request = new SearchingRequest
            {
                Keyword = string.Empty,
                IsPaging = false
            };

            _customers = _customerController.Search(request);
            _customers.Insert(0, new Customer { Id = -1, Name = string.Empty });
            cboCustomers.Properties.DataSource = _customers;
            cboCustomers.Properties.DisplayMember = "Name";
            cboCustomers.Properties.ValueMember = "Id";
        }

        #endregion

        private void btnPrintReport_Click(object sender, EventArgs e)
        {
            //var selectedRows = gvLiabilities.GetSelectedRows();
            //if (selectedRows.Count() <= 0)
            //{
            //    MessageBox.Show("Chọn khách hàng để in báo cáo");
            //    return;
            //}
            //var customerIds = selectedRows.ToList()
            //    .Select(selectedRow => _reportData[selectedRow]
            //                               .CustomerId)
            //    .ToList();
            //var customerInput = string.Join(",", customerIds);
            var customerIds = string.Join(",", _reportData
                                                   .Select(t => t.CustomerId)
                                                   .Distinct()
                                                   .ToArray());

            var reportParams = new Dictionary<string, object>
                                   {
                                       {
                                           "@startDate", string.Concat(daFromDate.DateTime.Year, "-",
                                                                       daFromDate.DateTime.Month, "-",
                                                                       daFromDate.DateTime.Day)
                                       },
                                       {
                                           "@endDate", string.Concat(daToDate.DateTime.Year, "-",
                                                                     daToDate.DateTime.Month, "-",
                                                                     daToDate.DateTime.Day)
                                       },
                                       {"@customerIds", customerIds}
                                   };

            var reportViewer = new FrmReportViewer(Constant.ReportFolder + "xrptCustomerLiability",
                                                   reportParams)
                                   {
                                       MdiParent = MdiParent
                                   };
            reportViewer.Show();
        }
    }
}
